package com.ruoyi.crm.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.crm.domain.CrmChecktel;
import com.ruoyi.crm.domain.CrmCustomer;
import com.ruoyi.crm.domain.CrmStatistics;
import com.ruoyi.crm.service.ICrmChecktelService;
import com.ruoyi.crm.service.ICrmCustomerService;
import com.ruoyi.crm.service.ICrmCustomerhisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 客户信息Controller
 * 
 * @author ruoyi
 * @date 2025-02-26
 */
@RestController
@RequestMapping("/crm/customer")
public class CrmCustomerController extends BaseController
{
    @Autowired
    private ICrmCustomerService crmCustomerService;

    @Autowired
    ICrmCustomerhisService crmCustomerhisService;

    @Autowired
    ICrmChecktelService crmChecktelService;

    /**
     * 查询客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(CrmCustomer crmCustomer) {
        startPage();
        List<SysRole> roleList = SecurityUtils.getLoginUser().getUser().getRoles();
        ArrayList<String> roles = new ArrayList<String>();
        for (SysRole role : roleList) {
            roles.add(role.getRoleKey());
        }
        crmCustomer.getParams().put("userId", SecurityUtils.getUserId());
        crmCustomer.getParams().put("deptId", SecurityUtils.getDeptId());
        crmCustomer.getParams().put("roles", roles.toString().replace("[", "").replace("]", "").replace(" ", ""));
        List<CrmCustomer> list = crmCustomerService.selectCrmCustomerList(crmCustomer);

        return getDataTable(list);
    }

    /**
     * 导出客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:export')")
    @Log(title = "客户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CrmCustomer crmCustomer)
    {
        List<CrmCustomer> list = crmCustomerService.selectCrmCustomerList(crmCustomer);
        ExcelUtil<CrmCustomer> util = new ExcelUtil<CrmCustomer>(CrmCustomer.class);
        util.exportExcel(response, list, "客户信息数据");
    }

    /**
     * 获取客户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {

        CrmCustomer crmCustomer = crmCustomerService.selectCrmCustomerById(id);

        if (crmCustomer.getLoaderContactInformation() != null && crmCustomer.getLoaderContactInformation().length() >= 4) {
            crmCustomer.setLoaderContactInformation(crmCustomer.getLoaderContactInformation().substring(0, 3) + "****" + crmCustomer.getLoaderContactInformation().substring(7, 11));
        }

        if (crmCustomer.getWifeContactInformation() != null && crmCustomer.getWifeContactInformation().length() >= 4) {
            crmCustomer.setWifeContactInformation(crmCustomer.getWifeContactInformation().substring(0, 3) + "****" + crmCustomer.getWifeContactInformation().substring(7, 11));
        }

        return success(crmCustomer);
    }

    /**
     * 新增客户信息
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:add')")
    @Log(title = "客户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CrmCustomer crmCustomer) {
        crmCustomer.setUpdateBy(getLoginUser().getUsername());
        int i = crmCustomerService.insertCrmCustomer(crmCustomer);
        crmCustomerService.insertCrmCustomerhis(crmCustomer);
        return toAjax(i);
    }

    /**
     * 修改客户信息
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:edit')")
    @Log(title = "客户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CrmCustomer crmCustomer) {

        Long id = crmCustomer.getId();
        CrmCustomer oldCrmCustomer = crmCustomerService.selectCrmCustomerById(id);

        crmCustomer.setUpdateBy(getLoginUser().getUsername());
        if (crmCustomer.getLoaderContactInformation() != null && crmCustomer.getLoaderContactInformation().contains("*")) {
            crmCustomer.setLoaderContactInformation(oldCrmCustomer.getLoaderContactInformation());
        }
        if (crmCustomer.getWifeContactInformation() != null && crmCustomer.getWifeContactInformation().contains("*")) {
            crmCustomer.setWifeContactInformation(oldCrmCustomer.getWifeContactInformation());
        }

        int i = crmCustomerService.updateCrmCustomer(crmCustomer);
        crmCustomerService.insertCrmCustomerhis(crmCustomer);
        return toAjax(i);
    }

    /**
     * 删除客户信息
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:remove')")
    @Log(title = "客户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        Integer i = 0;
        for (Long id : ids) {
            i = 0;
            CrmCustomer crmCustomer = crmCustomerService.selectCrmCustomerById(id);
            crmCustomer.setUpdateBy(getLoginUser().getUsername());
            crmCustomer.setDelFlag("2");
            crmCustomerService.updateCrmCustomer(crmCustomer);
            i = crmCustomerService.insertCrmCustomerhis(crmCustomer);
        }
        return toAjax(i);
    }

    @PreAuthorize("@ss.hasPermi('crm:customer:query')")
    @GetMapping(value = "checkTel/{id}")
    public AjaxResult getTelInfo(@PathVariable("id") Long id) {

        CrmCustomer crmCustomer = crmCustomerService.selectCrmCustomerById(id);
        CrmChecktel crmChecktel = new CrmChecktel();
        crmChecktel.setCrmCustomerId(id);
        crmChecktel.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        crmChecktel.setCrmCustomerName(crmCustomer.getLoaderName());
        crmChecktel.setUserName(SecurityUtils.getLoginUser().getUser().getUserName());
        crmChecktelService.insertCrmChecktel(crmChecktel);

        return success(crmCustomer);
    }

    @GetMapping(value = "/getCrmCustomerListStatic")
    public AjaxResult getStatic(CrmCustomer crmCustomer) {
        List<SysRole> roleList = SecurityUtils.getLoginUser().getUser().getRoles();
        ArrayList<String> roles = new ArrayList<String>();
        for (SysRole role : roleList) {
            roles.add(role.getRoleKey());
        }
        crmCustomer.getParams().put("userId", SecurityUtils.getUserId());
        crmCustomer.getParams().put("deptId", SecurityUtils.getDeptId());
        crmCustomer.getParams().put("roles", roles.toString().replace("[", "").replace("]", "").replace(" ", ""));
        List<CrmStatistics> list   = crmCustomerService.selectCrmCustomerListStatic(crmCustomer);
        return success(list);
    }


}
